package com.dream.dynamic_datasource.utils;

import com.dream.dynamic_datasource.entity.user.User;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @description: JWT工具类
 * @author: Luo
 * @create: 2020-06-22 14:16
 */
@Component
public class JwtUtil {
    @Autowired
    protected HttpServletRequest request;
    //@Autowired
    //protected HttpServletResponse response;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommonUtil commonUtil;

    private static final String SUBJECT="eye_of_the_park";
    private static final Long EXPIRE= 1000*60*30L;
    private static final String APP_SECRET = "eye_of_the_park";

    /**
     * 将token存入redis
     * @param user
     * @date 2020/6/22 14:24
     */
    public  String geneJsonWebToken(User user){
        String token =createToken(user);
        String tokenKey = commonUtil.MD5(user.getUserId() + "" + System.currentTimeMillis());
        if(StringUtils.isNotBlank(tokenKey)){
            redisUtil.setStringExpTime(tokenKey,token,EXPIRE+30L);
            return tokenKey;
        }
        return "null";
    }
    /**
     * 验证token失效时间
     * @date 2020/6/22 16:55
     */
    public User checkJWT(){
        String tokenKey = request.getHeader("Authorization");
        if(StringUtils.isBlank(tokenKey)){
            tokenKey=request.getParameter("Authorization");
        }
        try {
            String token = redisUtil.getString(tokenKey);
            final Claims  claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
            Integer id = (Integer) claims.get("id");
            String username = (String) claims.get("username");
            String dbName = (String) claims.get("dbName");
            User user = new User(id, username, dbName);
            redisUtil.setStringExpTime(tokenKey,createToken(user),EXPIRE+30L);
            return user;
        }  catch (Exception e) {
            return null;
        }


    }
    /**
     * 获取登录用户信息
     * @date 2020/6/22 16:55
     */
    public  User getLogUser(){
        try {
            String tokenKey = request.getHeader("Authorization");
            checkJWT();
            String token = redisUtil.getString(tokenKey);
            final Claims  claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token).getBody();
            Integer id = (Integer) claims.get("id");
            String username = (String) claims.get("username");
            String dbName = (String) claims.get("dbName");
            return new User(id, username,dbName);
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 生成token
     * @param user
     * @date 2020/6/22 16:56
     */
    private String createToken(User user){
        return Jwts.builder().setSubject(SUBJECT).claim("id", user.getUserId()).claim("username", user.getUserName())
                .claim("dbName", user.getDbName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET).compact();
    }
}
